const fs = require('fs').promises;
const path = require('path');

async function loadPlugins(pluginsDir, pluginManager) {
  try {
    const files = await fs.readdir(pluginsDir);
    const pluginPromises = [];
    
    for (const file of files) {
      const pluginPath = path.join(pluginsDir, file);
      const stat = await fs.stat(pluginPath);
      
      if (stat.isDirectory()) {
        // 检查是否存在 package.json 或 index.js
        try {
          const packageJsonPath = path.join(pluginPath, 'package.json');
          await fs.access(packageJsonPath);
          pluginPromises.push(pluginManager.loadPlugin(packageJsonPath));
        } catch {
          const indexPath = path.join(pluginPath, 'index.js');
          try {
            await fs.access(indexPath);
            pluginPromises.push(pluginManager.loadPlugin(indexPath));
          } catch {
            console.warn(`Plugin directory ${file} does not contain package.json or index.js`);
          }
        }
      }
    }
    
    await Promise.all(pluginPromises);
  } catch (error) {
    console.error('Error loading plugins:', error);
  }
}

module.exports = { loadPlugins };